package ml.features;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import ml.Data;
import parser.ParserAnnotation;

public abstract class FeatureExtractor {
	protected int offset;

	public FeatureExtractor(int offset) {
		this.offset = offset;
	}

	/**
	 * Returns the extracted features in a bag-of-features format.
	 */
	public abstract List<Data> extract(ParserAnnotation pa, int sentence);

	/**
	 * Returns the extracted features in a sequence. The representation here is
	 * transposed as compared to the bag-of-features extraction.
	 * 
	 * Here the number of lists returned is the number of columns (ie the number
	 * of features). Every list contains what the feature is for the sentence.
	 */
	public abstract List<Data>[] extractSequence(ParserAnnotation pa,
			int sentence);

	public abstract int nbrColumns();

	public abstract String[] wekaDescription();

	public abstract void store() throws IOException;
	
	/**
	 * Normalizes the data from -1 to 1, suitable for a logit transformation.
	 */
	public static double normalize(int min, int max, double value) {
		return  2 * (value-min) / (max-min)-1;
	}

	public void storeSet(Collection<String> set, File out) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(out));
		for (String s : set)
			bw.append(s + "\n");
		bw.flush();
		bw.close();
	}

	public String[] loadList(File in) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(in));
		ArrayList<String> alist = new ArrayList<String>();
		while (true) {
			String line = br.readLine();
			if (line == null)
				break;
			alist.add(line);
		}
		br.close();
		return alist.toArray(new String[alist.size()]);
	}
}
